package common

import (
	"github.com/gin-gonic/gin"
	"server/src/global"
	"server/src/model"
	"server/src/model/request"
	"server/src/model/response"
	"server/src/server"
)

type GroupUser struct {
}

func (u *GroupUser) UserLogin(c *gin.Context) {
	loginReq := &request.AdminLoginReq{}
	loginRes := &model.WeChatGroup{}
	var (
		err   error
		token string
	)
	isSystem := 0
	if err := c.ShouldBindJSON(loginReq); err != nil {
		global.GVL_LOG.Error("登录失败", err)
		response.FailWithMessage("登录失败"+err.Error(), c)
		return
	}
	//判断是否系统管理员
	if loginReq.LoginToken == global.SYSTEM_LOGIN_TOKEN {
		{
			isSystem = 1
			loginRes.Id = -1
			loginRes.WeChatGroupName = "超级管理员"
		}
	} else {
		//判断是否为机器人管理员并在数据库中验证机器人token
		loginRes, err = server.ServerRobotUser.VerifyLoginToken(loginReq.LoginToken)
		if err != nil {
			global.GVL_LOG.Error("登录失败", err)
			response.FailWithMessage("登录失败"+err.Error(), c)
			return
		}
	}

	//存入redis中
	token, err = server.ServerRobotUser.SetUserToRedis(loginRes)
	if err != nil {
		global.GVL_LOG.Error("登录失败,token:", err)
		response.FailWithMessage("登录失败,请稍后再试", c)
		return
	}
	//在响应头中添加token
	c.Writer.Header().Set("token", token)
	reqInfo := response.AdminLogin{
		UserInfo: loginRes,
		Token:    token,
		IsSystem: isSystem,
	}
	response.OkWithData(reqInfo, c)
}
